/*
 * Copyright 2010, 2011, 2012 mapsforge.org
 *
 * This program is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.plako.mapper.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.geojson.FeatureCollection;
import org.geojson.LngLatAlt;
import org.geojson.Polygon;
import org.mapsforge.core.GeoPoint;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author stef class that gets coordiantes from a geoJson File and returns a list of GeoPoints
 */
public class PointsExtractor {

	public static List<GeoPoint> getPoints(File geoJsonFile) {
		FeatureCollection featureCollection;
		try {

			InputStream is;
			is = new FileInputStream(geoJsonFile);
			featureCollection = new ObjectMapper().readValue(is, FeatureCollection.class);

		} catch (FileNotFoundException e) {

			e.printStackTrace();
			return null;
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

		Polygon polygon = (Polygon) featureCollection.getFeatures().get(0).getGeometry();
		if (polygon.getCoordinates() != null)
			return convertCoordinates(polygon.getCoordinates());
		return null;
	}

	private static List<GeoPoint> convertCoordinates(List<List<LngLatAlt>> coords) {

		List<GeoPoint> geoPoints = new ArrayList<GeoPoint>();
		for (List<LngLatAlt> listLl : coords) {
			for (LngLatAlt ll : listLl) {
				geoPoints.add(new GeoPoint(ll.getLatitude(), ll.getLongitude()));

			}

		}

		return geoPoints;
	}

}
